package com.kkb.retailer.center.controller;


import com.csvreader.CsvWriter;
import com.github.pagehelper.PageInfo;

import com.kkb.retailer.center.api.CategoryInfoService;
import com.kkb.retailer.center.common.http.HttpResult;
import com.kkb.retailer.center.common.pojo.CategoryInfo;
import com.kkb.retailer.center.common.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "商城:商品分类管理")
@RestController
@RequestMapping("api")
public class CategoryController {

    @Reference
    private CategoryInfoService categoryInfoService;

    @ApiOperation(value = "获取全部商品分类")
    @GetMapping(value = "/queryCategory")
    public HttpResult queryAllCategory(Integer page, Integer size){
        List<CategoryInfo> categories = categoryInfoService.selectAllCategory();
        PageInfo<CategoryInfo> pageInfo=new PageInfo<>(categories);
        return HttpResult.success(pageInfo);
    }

    @ApiOperation(value = "获取前两级商品分类")
    @GetMapping(value = "/queryCategoryLevel2")
    public HttpResult queryCategoryLevel2(){
        List<CategoryInfo> categories = categoryInfoService.selectCategoryLevel2();
        return HttpResult.success(categories);
    }

    @GetMapping(value = "/createCategoryCsv")
    public HttpResult createCsv(){

        String filePath = "/Users/hadoop/Desktop/test2.csv";
        int result = 0;
        try {
            // 创建CSV写对象
            CsvWriter csvWriter = new CsvWriter(filePath, ',', Charset.forName("utf-8"));
            // 写表头
            String[] headers = {"ID","分类名称", "父ID", "层级","顺序","状态"};

            csvWriter.writeRecord(headers);
            List<CategoryInfo> categories = categoryInfoService.selectAllCategory();
            result = categories.size();
            for(int i=0;i<categories.size();i++){
                CategoryInfo categoryInfo = categories.get(i);
                List<String> contentlist = new ArrayList<>();
                contentlist.add(String.valueOf(categoryInfo.getId()));
                contentlist.add(categoryInfo.getCategoryName());
                contentlist.add(String.valueOf(categoryInfo.getParentId()));
                contentlist.add(String.valueOf(categoryInfo.getLevel()));
                contentlist.add(String.valueOf(categoryInfo.getStatus()));
                contentlist.add(String.valueOf(categoryInfo.getSort()));


                String[] arry = contentlist.toArray(new String[contentlist.size()]);
                csvWriter.writeRecord(arry);
            }
            csvWriter.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return HttpResult.success(result);
    }

    @GetMapping("/downloadAllCategory")
    public void downloadAllCategory(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String fileName = "test2.csv";
        String realPath = "/Users/hadoop/Desktop";
        File file = new File(realPath,fileName);
        if(file.exists()){
            response.setHeader("content-type","application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"utf-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try{
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i!=-1){
                    os.write(buffer,0,i);
                    i = bis.read(buffer);
                }
                System.out.println("Downlad the song success");
            }catch (IOException e){
                e.printStackTrace();;
            }finally {
                if(bis!=null){
                    bis.close();;
                }
                if(fis!=null){
                    bis.close();
                }
            }


        }
    }


    @PostMapping("/upload")
    public HttpResult uploadFile(@RequestParam("file") MultipartFile multipartFile){
        String result = null;
        String directory = "/Users/hadoop/Desktop";

        File file = FileUtil.toFile(multipartFile,directory);
        try {
            boolean b = file.createNewFile();
            result = file.getName();
        } catch (IOException e) {
            e.printStackTrace();
            result = e.getMessage();
        }
        System.out.println(file.getName());
        return HttpResult.success(result);
    }


}
